import { CloseCircleTwoTone, DiffOutlined } from "@ant-design/icons";
import { Badge, Button, Empty, FloatButton, Popover, Space } from "antd";
import React, { useEffect, useState } from "react";
import { evaluationDiffUuidsStorage } from "@/utils/storage";
import { useMemoizedFn, useRequest } from "ahooks";
import {history} from '@umijs/max';
import { evaluationV1ControllerBatchTitle } from "@/services/auto/evaluation";

const initValue = {
  evaluationUuids: [],
  evaluationComposeUuids: [],
  eqUuids: [],
};
export default function DiffBtn(){
  const [uuids, setUuids] = useState<{
    evaluationUuids: string[];
    evaluationComposeUuids: string[];
    eqUuids: string[];
  }>(initValue);

  const count = uuids.evaluationComposeUuids.length + uuids.evaluationUuids.length + uuids.eqUuids.length;

  const {data: titleData} = useRequest(()=>{
    return evaluationV1ControllerBatchTitle({
      evaluationUuids: uuids.evaluationUuids.join(','),
      evaluationComposeUuids: uuids.evaluationComposeUuids.join(','),
      eqUuids: uuids.eqUuids.join(','),
    })
  }, {
    ready: count > 0,
    refreshDeps: [uuids],
  })

  const refresh = useMemoizedFn(()=>{
    const evaluationDiffUuids = evaluationDiffUuidsStorage.get();
    if(evaluationDiffUuids){
      setUuids({
        evaluationUuids: evaluationDiffUuids.evaluationUuids ?? [],
        evaluationComposeUuids: evaluationDiffUuids.evaluationComposeUuids ?? [],
        eqUuids: evaluationDiffUuids.eqUuids ?? [],
      })
    }else{
      setUuids(initValue)
    }
  })

  useEffect(() => {
    refresh();

    const listener = (e: MessageEvent<{type: string}>)=>{
      if(e.data?.type === "evaluationDiffChangeByAddDiffBtn"){
        refresh();
        setShowPopover(true);
      }
    }
    const storageListener = (e: StorageEvent)=>{
      if(e.key === "EVALUATION_DIFF_UUIDS_V2"){
        refresh();
      }
    }
    window.addEventListener('message', listener)
    window.addEventListener('storage', storageListener)
    return ()=>{
      window.removeEventListener('message', listener);
      window.removeEventListener('storage', storageListener);
    }
  }, []);

  const [showPopover, setShowPopover       ] = useState<boolean>(false);

  return <Popover open={showPopover} onOpenChange={setShowPopover} content={
    count === 0 ? <Empty description="快去添加对比数据吧" /> :<div>
      <div className="mb-[8px] font-bold" style={{fontSize: 16}}>参与对比项：</div>
      <div className="mb-[8px]">
        {titleData?.map((item, index)=>{
          return <div key={item.uuid} className="mb-[4px] flex gap-[4px] justify-between">
            <div>{index+1}. {item.title}</div>
            <CloseCircleTwoTone className="cursor-pointer" onClick={()=>{
              const data = evaluationDiffUuidsStorage.get();
              if(item.belong === 'evaluation' && data?.evaluationUuids) {
                data.evaluationUuids = data.evaluationUuids.filter(it=>it !== item.uuid);
              }
              if(item.belong === 'evaluationCompose' && data?.evaluationComposeUuids){
                data.evaluationComposeUuids = data.evaluationComposeUuids.filter(it=>it !== item.uuid);
              }
              if(item.belong === 'eq' && data?.eqUuids){
                data.eqUuids = data.eqUuids.filter(it=>it !== item.uuid);
              }
              if(data) {
                evaluationDiffUuidsStorage.set(data);
                refresh();
                postMessage({
                  type: 'evaluationDiffChangeByDiffBtn'
                })
              }
            }} />
          </div>
        })}
      </div>
      <Space size={8}>
        <Button type="primary" size="small" onClick={()=>{
          if(!count) {
            return;
          }

          const searchParams = new URLSearchParams();
          if(uuids.evaluationUuids.length){
            searchParams.set('evaluationUuids',uuids.evaluationUuids.join(',') );
          }
          if(uuids.evaluationComposeUuids.length){
            searchParams.set('evaluationComposeUuids',uuids.evaluationComposeUuids.join(',') );
          }
          if(uuids.eqUuids.length){
            searchParams.set('eqUuids',uuids.eqUuids.join(',') );
          }
          const href = history.createHref({
            pathname: '/evaluation-diff',
            search: searchParams.toString(),
          })
          window.open(href);
        }}>开始对比</Button>
        <a onClick={()=>{
          evaluationDiffUuidsStorage.remove();
          refresh();
          postMessage({
            type: 'evaluationDiffChangeByDiffBtn'
          })
        }}>清空所有型号</a>
      </Space>
    </div>
  } placement="topLeft" trigger="click">
    <Badge styles={{
      root: {
        position: 'fixed',
        bottom: 96,
        right: 24,
      }
    }} count={count}>
      <Button size="large" shape="circle" type="primary" icon={<DiffOutlined />} id="diff-btn" />
    </Badge>
  </Popover>
}
